module LPM
  class Proc

    class << self
      def cpuinfo(*arguments)
        begin
          cpus_info = IO.read('/proc/cpuinfo').split("#{$/*2}")
          return cpus_info.map do |cpu_info|
            h = {}
            cpu_info.split($/).each do |line|
              kv = line.split(/\s*\:\s*/)
              h[kv[0]] = kv[1]
            end
            h
          end
        rescue Exception => e
          # => do nothing
          return "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
        ensure
        end
      end

      def meminfo(*arguments)
        begin
          mem_info = IO.read('/proc/meminfo')
          h = {}
          mem_info.split($/).each do |line|
            kv = line.split(/\s*\:\s*/)
            h[kv[0].to_sym] = kv[1].chomp(' kB')
          end
          h
        rescue Exception => e
          # => do nothing
          return "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
        ensure
        end
      end

      def loadavg(*arguments)
        begin
          load_avg = IO.read('/proc/loadavg').split(/\s+/)
          h = {}
          h[:last] = load_avg.pop
          h[:running],h[:total] = load_avg.pop.split(/\//)
          h[:load] = load_avg
          h
        rescue Exception => e
          # => do nothing
          return "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
        ensure
        end
      end

      def uptime(*arguments)
        begin
          total,idle = IO.read('/proc/uptime').split
          {:total=>total,:idle=>idle}
        rescue Exception => e
          # => do nothing
          return "{\"exception\":\"#{e.class}\",\"msg\":\"#{e}\"}"
        ensure
        end
      end
    end
    
  end
end